package com.parking.carsystem.parkingchargesystem.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.GetRequest;
import com.parking.carsystem.parkingchargesystem.R;
import com.parking.carsystem.parkingchargesystem.activity.ChooseLisencePlateActivity;
import com.parking.carsystem.parkingchargesystem.activity.CouponActivity;
import com.parking.carsystem.parkingchargesystem.activity.LicensePlateAddActivity;
import com.parking.carsystem.parkingchargesystem.activity.MainActivity;
import com.parking.carsystem.parkingchargesystem.activity.MapActivity;
import com.parking.carsystem.parkingchargesystem.activity.PayMentRecordActivity;
import com.parking.carsystem.parkingchargesystem.activity.SelfServicePaymentActivity;
import com.parking.carsystem.parkingchargesystem.adapter.ViewpagerAdapter;
import com.parking.carsystem.parkingchargesystem.common.CarApp;
import com.parking.carsystem.parkingchargesystem.common.Constant;
import com.parking.carsystem.parkingchargesystem.module.HomeTopMessageModel;
import com.parking.carsystem.parkingchargesystem.module.ListDefaultOrderModule;

import java.util.ArrayList;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

public class HomeFragment extends Fragment implements ViewPager.OnPageChangeListener, View.OnClickListener {
    Unbinder unbinder;
    @BindView(R.id.view_page_image)
    ViewPager viewPage;
    @BindView(R.id.dots_layout)
    LinearLayout dotsLayout;
    @BindView(R.id.layout_image)
    RelativeLayout layoutImage;
    @BindView(R.id.add_parking_plate)
    TextView addParkingPlate;
    @BindView(R.id.paking_plate_name)
    TextView pakingPlateName;
    @BindView(R.id.parking_status)
    TextView parkingStatus;
    @BindView(R.id.parkinglotName)
    TextView parkinglotName;
    @BindView(R.id.parking_message)
    RelativeLayout parkingMessage;
    @BindView(R.id.switch_lisense_plate)
    RelativeLayout switchLisensePlate;
    @BindView(R.id.company_image)
    ImageView companyImage;
    @BindView(R.id.image)
    ImageView image;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.layout_pay)
    RelativeLayout layoutPay;
    @BindView(R.id.image1)
    ImageView image1;
    @BindView(R.id.name1)
    TextView name1;
    @BindView(R.id.layout_park)
    RelativeLayout layoutPark;
    @BindView(R.id.image2)
    ImageView image2;
    @BindView(R.id.name2)
    TextView name2;
    @BindView(R.id.layout_record)
    RelativeLayout layoutRecord;
    @BindView(R.id.image3)
    ImageView image3;
    @BindView(R.id.name3)
    TextView name3;
    @BindView(R.id.layout_coupon)
    RelativeLayout layoutCoupon;
    @BindView(R.id.recycle_data)
    LinearLayout recycleData;
    @BindView(R.id.refresh_image)
    ImageView refreshImage;
    private boolean parkingCarStatus;


    private ArrayList<HomeTopMessageModel> imageData;
    private MainActivity mActivity;
    private long delayMillis = 4000;
    public int START_VIEW = 1;
    public int STOP_VIEW = 2;
    public Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            handleMessageMeathed(msg);
        }
    };

    public void handleMessageMeathed(Message msg) {
        switch (msg.what) {
            case 1:
                viewPage.setCurrentItem(viewPage.getCurrentItem() + 1);
                break;
            case 2:
                handler.removeCallbacksAndMessages(null);
                break;
        }
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.fragment_home, container, false);
        unbinder = ButterKnife.bind(this, inflate);
        initView();
        return inflate;
    }

    private void initView() {
        mActivity = (MainActivity) getActivity();
        addParkingPlate.setOnClickListener(this);
        layoutPay.setOnClickListener(this);
        layoutPark.setOnClickListener(this);
        layoutRecord.setOnClickListener(this);
        layoutCoupon.setOnClickListener(this);
        if (imageData == null) {
            imageData = new ArrayList<>();
            HomeTopMessageModel model = new HomeTopMessageModel(R.mipmap.banner1, "水懂我心, 自然淮安", "千亿国联, 服务淮安");
            HomeTopMessageModel model1 = new HomeTopMessageModel(R.mipmap.banner2, "淮安国联集团", "城市综合服务运营商");
            HomeTopMessageModel model2 = new HomeTopMessageModel(R.mipmap.banner3, "智慧停车", "让生活更美好");
            imageData.add(model);
            imageData.add(model1);
            imageData.add(model2);
        }
        addPoint();
        ViewpagerAdapter viewpagerAdapter = new ViewpagerAdapter();
        viewpagerAdapter.setArrayList(imageData, mActivity);
        viewPage.addOnPageChangeListener(this);
        viewPage.setAdapter(viewpagerAdapter);
        viewPage.setCurrentItem(Integer.MAX_VALUE / 2 - (Integer.MAX_VALUE / 2 % imageData.size()));
        handler.sendEmptyMessageDelayed(START_VIEW, delayMillis);
        switchLisensePlate.setOnClickListener(this);

        getGroupList("");
        Intent intent = null;
    }


    /**
     * 添加小圆点
     */
    private void addPoint() {
        for (int i = 0; i < imageData.size(); i++) {
            LinearLayout.LayoutParams pointParams =
                    new LinearLayout.LayoutParams(20,
                            20);
            if (i < 1) {
                pointParams.setMargins(0, 0, 0, 0);
            } else {
                pointParams.setMargins(20, 0, 0, 0);
            }
            ImageView iv = new ImageView(mActivity);
            iv.setLayoutParams(pointParams);
            iv.setBackgroundResource(R.drawable.shape_point_normal);
            dotsLayout.addView(iv);
        }
        dotsLayout.getChildAt(0).setBackgroundResource(R.drawable.shape_point_select);
    }

    /**
     * 判断小圆点
     */
    private void monitorPoint(int position) {
        for (int i = 0; i < imageData.size(); i++) {
            if (i == position) {
                dotsLayout.getChildAt(position).setBackgroundResource(R.drawable.shape_point_select);
            } else {
                dotsLayout.getChildAt(i).setBackgroundResource(R.drawable.shape_point_normal);
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        handler.removeCallbacksAndMessages(null);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {
        int newposition = position % imageData.size();
        monitorPoint(newposition);
    }

    @Override
    public void onPageScrollStateChanged(int state) {
        switch (state) {
            //用户滑动时停止轮播
            case ViewPager.SCROLL_STATE_DRAGGING:
                handler.sendEmptyMessage(STOP_VIEW);
                break;
            //用户滑动完成时继续轮播
            case ViewPager.SCROLL_STATE_IDLE:
                handler.sendEmptyMessageDelayed(START_VIEW, delayMillis);
                break;
        }
    }

    public void getGroupList(String plateNumber) {
        GetRequest<String> stringGetRequest;
        if (!TextUtils.isEmpty(plateNumber)) {
            stringGetRequest = OkGo.<String>get(Constant.url + Constant.ORDERLISTDEFAULTORDER).params("plateNumber", plateNumber);
        } else {
            stringGetRequest = OkGo.<String>get(Constant.url + Constant.ORDERLISTDEFAULTORDER);
        }
        stringGetRequest
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        try {
                            Gson gson = new Gson();
                            ListDefaultOrderModule listDefaultOrderModule = gson.fromJson(response.body(), ListDefaultOrderModule.class);
                            if (listDefaultOrderModule.code == 200) {
                                if (listDefaultOrderModule.total != 0) {
                                    parkingCarStatus = true;
                                    addParkingPlate.setVisibility(View.GONE);
                                    switchLisensePlate.setVisibility(View.VISIBLE);
                                    CarApp.rowsBean = listDefaultOrderModule.rows.get(0);
                                    if (CarApp.rowsBean != null) {
                                        pakingPlateName.setText(CarApp.rowsBean.plateNumber);
                                        if (CarApp.rowsBean.status == 0) {
                                            parkingStatus.setText("已扫码");
                                        } else if (CarApp.rowsBean.status == 1) {
                                            parkingStatus.setText("已入场");
                                        } else if (CarApp.rowsBean.status == 2) {
                                            parkingStatus.setText("已预支付");
                                        } else if (CarApp.rowsBean.status == 3) {
                                            parkingStatus.setText("已支付");
                                        } else if (CarApp.rowsBean.status == 4) {
                                            parkingStatus.setText("已出场");
                                        }
                                        parkinglotName.setText(CarApp.rowsBean.parkinglotName);
                                    }
                                } else {
                                    parkingCarStatus = false;
                                    switchLisensePlate.setVisibility(View.GONE);
                                    addParkingPlate.setVisibility(View.VISIBLE);
                                }
                            } else {
                                addParkingPlate.setVisibility(View.VISIBLE);
                                switchLisensePlate.setVisibility(View.GONE);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        addParkingPlate.setVisibility(View.VISIBLE);
                        switchLisensePlate.setVisibility(View.GONE);
                    }
                });
    }

    @Override
    public void onClick(View v) {
        Intent intent = null;
        switch (v.getId()) {
            case R.id.switch_lisense_plate:
                intent = new Intent(mActivity, ChooseLisencePlateActivity.class);
                startActivityForResult(intent, 0);
                break;
            case R.id.add_parking_plate:
                intent = new Intent(mActivity, LicensePlateAddActivity.class);
                startActivityForResult(intent, 0);
                break;
            case R.id.layout_pay:
                if (parkingCarStatus) {
                    intent = new Intent(mActivity, SelfServicePaymentActivity.class);
                    intent.putExtra(Constant.PLATENUMBER, CarApp.rowsBean.plateNumber);
                    startActivity(intent);
                } else {
                    mActivity.showToast("请添加车牌");
                }
                break;
            case R.id.layout_park:
                intent = new Intent(mActivity, MapActivity.class);
                startActivity(intent);
                break;
            case R.id.layout_record:
//                if (parkingCarStatus) {
                    intent = new Intent(mActivity, PayMentRecordActivity.class);
                    //不需要了
//                intent.putExtra(Constant.PLATENUMBER, CarApp.rowsBean.plateNumber);
                    startActivity(intent);
//                } else {
//                    mActivity.showToast("请添加车牌");
//                }
                break;
            case R.id.layout_coupon:
                //优惠券页面
                if (parkingCarStatus) {
                    intent = new Intent(mActivity, CouponActivity.class);
                    intent.putExtra(Constant.PLATENUMBER, CarApp.rowsBean.plateNumber);
                    startActivity(intent);
                } else {
                    mActivity.showToast("请添加车牌");
                }
                break;
        }
    }
}
